<template>
  <li>
    <label>
      <input type="checkbox" :checked="todo.done" @change="handleCheck(todo.id)"/>
      <span v-show="!todo.isEdit">{{ todo.title }}</span>
      <input
          type="text"
          v-show="todo.isEdit"
          :value="todo.title"
          @blur="handlerBlur(todo, $event)"
          ref="inputTitle">
    </label>
    <button class="btn btn-edit" v-show="!todo.isEdit" @click="handleEdit(todo)">编辑</button>
    <button class="btn btn-danger" @click="handleDelete(todo.id)">删除</button>
  </li>
</template>

<script>
import pubsub from "pubsub-js"

export default {
  name: 'MyItem',
  // 声明接收todo对象
  props: ['todo'],
  methods: {
    handleCheck(id) {
      // 通知 App 组件将对应的todo对象的 done 值取反
      this.$bus.$emit('checkTodo', id)
    },
    handleDelete(id) {
      if (confirm('确定删除吗？')) {
        pubsub.publish('deleteTodo', id)
      }
    },
    handleEdit(todo) {
      if (todo.hasOwnProperty('isEdit')) {
        todo.isEdit = true
      } else {
        this.$set(todo, 'isEdit', true)  // 响应式添加
      }

      // TODO nextTick 方法会在 DOM 模板重新解析完后再执行
      this.$nextTick(function () {
        this.$refs.inputTitle.focus()
      })
    },
    handlerBlur(todo, event) {
      todo.isEdit = false

      // 修改逻辑
      if (!event.target.value.trim()) {
        alert('输入不能为空')
        return
      }
      this.$bus.$emit('updateTodo', todo.id, event.target.value)
    }
  }
}
</script>

<style scoped>
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}

li:hover {
  background-color: #dddddd;
}

li:hover button {
  display: block;
}
</style>